<script setup>
import { ref, computed, onMounted, reactive, } from 'vue'
import img1 from './imgs/dou.png'
import img2 from './imgs/wei.png'
import { useRouter, useRoute } from "vue-router";
import request from "@/common/utils/request";
import {
    ExclamationCircleOutlined
} from "@ant-design/icons-vue";
const router = useRouter();
import utils from "@/common/utils/utils.js";

import { message } from "ant-design-vue";
import { nanoid } from 'nanoid';

const route = useRoute();

// 路由参数  
const query = computed(() => {
    return {
        id: route.query?.id
    }
})



// 获取外链数据
const getLinkArr = async () => {
    const res = await request.get('work_ai', '/user/shotstack/toReachCustomers/list')
    console.log(res, '微信外链列表');
    if (Array.isArray(res.result?.data)) {
        const filterArr = res.result?.data.filter(ele => {
            return ele.status == 1
        })
        state.linkArr = filterArr || []
    }
}

const getDetail = async () => {
    const res = await request.get('work_ai', '/user/shotstack/reachCustomersCards/detail', {
        id: query.value.id
    })
    console.log(res, '查看详情');
    for (let key in formState) {
        formState[key] = res.result[key]
    }
    // // 初始赋值
    linkFileList.value.push({
        uid: res.result.card_logo,
        status: 'done',
        response: {
            data: {
                fileName: res.result?.card_logo_name || '素材',
                fileUrl: res.result.card_logo
            }
        },
        name: res.result?.card_logo_name || '素材'
    })

}

const typeList = ref([
    { id: 'douyin', img: img1, name: '抖音' },
    // { id: 2, img: img2, name: '微信' },
])

const formState = reactive({
    // 当前选择的卡片类型
    card_type: 'douyin',
    // 选择的外链id
    reach_customers_id: null,
    // 卡片名称
    card_name: '',
    // 卡片描述
    card_desc: '',
    // 卡片logo
    card_logo: '',
    // 卡片描述
    card_desc: '',
    // 跳转类型
    reach_type: 'WeiXin',
    // 卡片跳转链接 - 个人
    link_type: 'Personal', // WeChat - 企微
    // card_status: 2, // 1-启用 2-停用
})

const state = reactive({
    linkArr: []
})

const formRef = ref(null)

const linkFileList = ref([])

// 上传图片
const handleChange = (info) => {
    console.log(info, '上传中...');
    if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
        console.log(info, 'info');
        console.log(linkFileList.value, '文件对象');
        formState.card_logo = info.file.response.data.fileUrl;
    } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
    }
}

// 验证图片
const linkFileListValid = async () => {
    if (!linkFileList.value.length) {
        return Promise.reject('请上传链接图片!')
    } else {
        return Promise.resolve();
    }
}

const submit_done = ref(false)

const back = () => {
    router.push({
        name: 'TiktoktoWechat',
        query: {
            type: 'cart'
        }
    })
}

// 创建卡片
const submitCreatCart = async () => {

    try {

        await formRef.value.validateFields()
        if (linkFileList.value[0].status != 'done') {
            return message.warn('图片正在上传中, 请稍后再试!')
        }

        if (submit_done.value) return

        submit_done.value = true
        // 判断是新增还是修改
        const sendType = query.value.id ? {
            url: '/user/shotstack/reachCustomersCards/update',
            type: 'put',
            msg: '修改成功!'
        } : {
            url: '/user/shotstack/reachCustomersCards/add',
            type: 'post',
            msg: '创建成功!'
        }


        const res = await request[sendType.type]('work_ai', sendType.url, {
            ...formState,
            id: query.value?.id || undefined
        })
        console.log(res, ' 卡片创建');
        if (res.result) {
            message.success(sendType.msg);

            setTimeout(() => {
                back()
            }, 500)
        }


    } catch (error) {
        // debugger

        console.log(error);
    }
}

// 删除已上传列表中的某项
const delImg = (type, file, fileList) => {
    console.log(file, fileList, '删除某项');
    const index = linkFileList.value.findIndex(ele => ele.uid == file.uid)
    index != -1 && linkFileList.value.splice(index, 1);
}


const handlechange = (e) => {
    state.linkArr.forEach(item => {
        if (e == item.id) {
            formState.card_name = item.link_name
            formState.card_desc = item.link_des
            formState.card_logo = item.link_image
            linkFileList.value = []
            linkFileList.value.push({
                uid: item.link_image,
                status: 'done',
                response: {
                    data: {
                        fileName: '素材',
                        fileUrl: item.link_image
                    }
                },
                name:'素材'
            })
        }
    })
}


onMounted(() => {
    getLinkArr()

    // debugger
    if (query.value.id) {
        getDetail()
        return
    }
    // 设置素材图片默认值
    linkFileList.value = [
        {
            uid: nanoid(),
            status: 'done',
            response: {
                data: {
                    fileName: '卡片logo',
                    fileUrl: utils.staticPath + "images/workAi/shotstack/short_card_share.jpg"
                    // fileUrl: img1
                }
            },
            name: '卡片logo'
        }
    ]
    formState.card_logo = utils.staticPath + "images/workAi/shotstack/short_card_share.jpg"
    // formState.card_logo = img1

})
</script>

<template>
    <a-alert message="本平台积极配合警方反诈工作！应公安部要求，我们将对生成的内容进行检测，如发现违反法律法规（包括但不限于诈骗，色情，贷款，博彩，赌球等）,则立即封禁相关账号，且不予退款。" banner
        closable style=' width:111.7%; margin-top:-10px; margin-bottom: 10px; margin-left:-15px; ' />

    <div class="container">
        <div class="header_box">
            <a-button @click="back">返回</a-button>
        </div>

        <div class="all_content_box">
            <div class="left_box">
                <!-- 每一个头部卡片类型 -->
                <div class="title_item_box">
                    <a-sapce direction="vertical">
                        <div class="content_item_title">
                            <div class="blue-box"></div>
                            <p class="cart_type_title">
                                自定义卡片分享
                            </p>
                        </div>

                        <div class="content_item">
                            <!-- 卡片类型的按钮 -->
                            <div>
                                <a-alert message="卡片标题和描述请勿填写违反法律法规的引流文案，否则此功能将被停用。" type="warning" show-icon
                                    style='margin-left:10px;margin-right:10px;' />
                            </div>

                            <div class="content_show_box">
                                <!-- 表单内容 -->
                                <div class="form_content">
                                    <a-form ref="formRef" style="width: 100%; margin-top: 20px" :model="formState"
                                        :label-col="{ style: { width: '100px' } }" :wrapper-col="{ span: 20 }">
                                        <a-form-item label="选择外链" name="reach_customers_id"
                                            :rules="[{ required: true, message: '请选择外链!', trigger: 'change' }]">
                                            <a-select style="width: 300px;" v-model:value="formState.reach_customers_id"
                                                allowClear showSearch @search="searchListData" @change="handlechange"
                                                optionFilterProp="children" :filter-option="false" placeholder="请选择外链">
                                                <a-select-option :value="item.id" v-for='item in state.linkArr'
                                                    :key='index'>
                                                    {{ item.link_name }}
                                                </a-select-option>
                                            </a-select>
                                        </a-form-item>

                                        <a-form-item label="卡片名称" name="card_name"
                                            :rules="[{ required: true, message: '请输入卡片名称!', trigger: 'change' }]">
                                            <a-input :maxlength="60" placeholder="请输入卡片名称"
                                                v-model:value="formState.card_name" allowClear />
                                        </a-form-item>
                                        <a-form-item name="card_desc" label="卡片描述"
                                            :rules="[{ required: true, message: '请输入卡片描述!', trigger: 'change' }]">
                                            <a-input :maxlength="60" v-model:value="formState.card_desc"
                                                placeholder="请输入卡片描述" allowClear />
                                        </a-form-item>

                                        <a-form-item label="卡片logo" name="linkFileList"
                                            :rules="[{ required: true, validator: linkFileListValid, message: '请上传卡片logo!', trigger: 'change' }]">
                                            <a-upload v-model:file-list="linkFileList" :maxCount="1"
                                                :action="$utils.sendImg"
                                                :headers="{ 'org-token': $store.getters.token }" @change="handleChange"
                                                :multiple="false" name="image" :data="{ dir: 'work_ai' }"
                                                accept=".png,.gif,.jpeg,.jpg">
                                                <a-button>
                                                    <upload-outlined></upload-outlined>
                                                    上传文件
                                                </a-button>
                                                <template #itemRender="{ file, fileList }">
                                                    <div class="img_box">
                                                        <a-spin tip="上传中..." size="small"
                                                            v-if="file.status === 'uploading'" />
                                                        <!-- <img :src="file?.response?.data?.fileUrl" alt="" v-else /> -->
                                                        <a-image v-else style="max-height: 40px;"
                                                            :src="file?.response?.data?.fileUrl" />
                                                        <a-popconfirm title="确定删除此项吗?" ok-text="确定" cancel-text="取消"
                                                            @confirm="delImg('linkFileList', file, fileList)">
                                                            <a-button @click.stop="() => { }" class="btn" type="link"
                                                                v-show="file.status === 'done'">删除</a-button>
                                                        </a-popconfirm>
                                                    </div>
                                                </template>
                                            </a-upload>
                                        </a-form-item>

                                        <!-- <a-form-item label="开启跳转">
                                    <div style='display:flex;align-items: center;'>
                                        <a-switch v-model:checked="formState.card_status" :checkedValue="1"
                                            :unCheckedValue="2" />
                                        <span style='margin-left:10px; white-space: nowrap;'>
                                            <ExclamationCircleOutlined style='color:#3664E0' />
                                        </span>
                                    </div>
                                </a-form-item> -->
                                        <a-button type="primary" style="margin-left: 20px; width:200px;" size="large"
                                            @click="submitCreatCart">
                                            {{
                                                query.id ? '保存' : '立即创建卡片'
                                            }}
                                        </a-button>
                                    </a-form>

                                </div>

                                <div class="right_box">
                                    <!-- 右边的预览效果  -->
                                    <div style="width:370px;height:345px;border-left:1px solid #F5F5F6;">
                                        <div style='padding:0px 20px 10px;'>
                                            <!-- <p>{{ }}</p> -->
                                            <div>
                                                <div class="right_cart_title" style="margin-left:100px; margin-bottom: 15px;
                                display:flex;align-items:center; ">
                                                    <img :src="img1" alt=""
                                                        style='width:20px; vertical-align: middle; height:20px;margin-right:5px;'>
                                                    <p style="line-height: 20px; margin: 0;">{{ '抖音私聊' }}</p>
                                                </div>
                                                <div horizontal
                                                    style='width:330px;height:100px;padding:10px 20px;background-color: #FFF;border-radius:10px;box-shadow: 0px 1px 15px 0px #CCCC; display: flex; align-items: center; gap: 10px;'>
                                                    <div
                                                        style='width:70px;height:70px;margin-top: 5px; background-color:#E8E8E8;border-radius: 10px;'>
                                                        <a-image v-if='formState.card_logo' :width="70"
                                                            style='border-radius:10px;height:70px;'
                                                            :src="formState.card_logo" />
                                                        <p style='text-align: center; line-height: 70px;' v-else>{{
                                                            'logo'
                                                            }}</p>
                                                    </div>
                                                    <div style='width:240px;margin-left:10px;'>
                                                        <p style='overflow: hidden;text-overflow: ellipsis; white-space: nowrap;font-size:15px;font-weight:900;margin-bottom:0px;padding-right: 20px;'
                                                            v-if='formState.card_name'>{{ formState.card_name }}</p>
                                                        <p style='overflow: hidden;text-overflow: ellipsis; white-space: nowrap;font-size:15px;font-weight:900;margin-bottom:0px;'
                                                            v-else>{{ '您的推广标题' }}</p>
                                                        <span
                                                            style='margin-top: 5px; color:#999999;overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; width: 100%; padding-right: 20px;'
                                                            v-if='formState.card_desc'>{{ formState.card_desc }}</span>
                                                        <span
                                                            style='margin-top: 5px;color:#999999;overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; width: 100%;'
                                                            v-else>{{ '您的内容详情描述' }}</span>
                                                    </div>
                                                </div>
                                            </div>

                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </a-sapce>
                </div>
            </div>



        </div>
        <!-- 每一个头部卡片类型 -->
        <!-- <div class="title_item_box">
            <a-sapce direction="vertical">
                <div class="content_item_title">
                    <div class="blue-box"></div>
                    <p class="cart_type_title">
                        选择外链
                    </p>
                </div>

                <div class="content_item"> -->
        <!-- 卡片类型的按钮 -->
        <!-- <div>
                        <a-button class="mr-10" @click="formState.card_type = item.id" v-for="item in typeList"
                            :key='item.id' :class="{ 'selected': formState.card_type === item.id }">
                            <a-flex align='center'>
                                <img :src='item.img' v-if='item.img'
                                    style='width:25px;height:25px;margin-right:10px;background-size:100% 100%;' />
                                {{ item.name }}
                            </a-flex>
                        </a-button>
                    </div> -->

        <!-- @select="handleSelectChange" margin-top: 15px;-->
        <!-- <a-select style="width: 300px;" v-model:value="formState.reach_customers_id" allowClear showSearch
                        @search="searchListData" optionFilterProp="children" :filter-option="false" placeholder="请选择外链">
                        <a-select-option :value="item.id" v-for='item in state.linkArr' :key='index'>
                            {{ item.link_name }}
                        </a-select-option>
                    </a-select>
                    <span class="tips_msg" v-show="!formState.reach_customers_id && showTips.reach_customers_id">
                        请选择外链!
                    </span>
                </div>
            </a-sapce>
        </div> -->





    </div>
</template>

<style lang="less" scoped>
.container {
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;

    .header_box {
        display: flex;
        height: 32px;
        line-height: 32px;
        margin-bottom: 20px;

        button {
            border-radius: 5px;
            margin-right: 5px
        }
    }

    .all_content_box {
        display: flex;
        gap: 10%;
    }
}

.tips_msg {
    color: var(--ss-error-color);
    font-size: 14px;
}

.title_item_box {
    margin-bottom: 20px;

    .content_item {
        margin-top: 5px;
        width: 1070px;
        display: flex;
        flex-direction: column;

        .content_show_box {

            display: flex;
            gap: 249px;

            .form_content {
                .img_box {
                    // cursor: pointer;
                    margin-top: 10px;
                    padding: 5px;
                    border: 1px solid #dde2e9;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    .btn {
                        padding: 0;
                        margin: 0;
                    }

                    // img {
                    //     max-width: 40px;
                    //     max-height: 40px;
                    //     object-fit: cover;
                    //     border-radius: 10px;
                    // }
                }
            }

            .right_box {
                padding-top: 20px;
            }
        }

    }

    .content_item_title {
        display: flex;
        align-items: center;
        font-size: 14px;
        font-weight: normal;
        margin-bottom: 20px;

        .cart_type_title {
            font-size: 14px;
            font-weight: normal;
            margin: 0;
        }

        .blue-box {
            width: 3px;
            height: 24px;
            margin-right: 10px;
            border-radius: 6px;
            background-color: #3C9CFF;
        }
    }
}

.error-border {
    border-color: red !important;
    /* 注意可能需要!important来覆盖其他样式 */
}

.error-message {
    color: red;
    margin-top: 5px;
}

.mr-10 {
    width: 140px;
    height: 50px;
    background-color: #F1F2F4;
    border: none;
    margin-right: 10px;

}

.mr-10.selected {
    /* 当按钮被选中时的样式 */
    background-color: #F0F6FF;
    border: 1px solid #4096FF;
    color: #1677FF;
}

.mr-box {
    width: 175px;
    height: 50px;
    background-color: #F1F2F4;
    border: none;
    margin-right: 10px;
    margin-top: 15px;
}

.mr-box.selected {
    /* 当按钮被选中时的样式 */
    background-color: #F0F6FF;
    border: 1px solid #4096FF;
    color: #1677FF;
}

.way-bg-type {
    max-width: 80px;
    max-height: 80px;
    position: relative;
}



// :deep(.ant-form-horizontal .ant-form-item-label){
// 	margin-top:-30px;
// }
// :deep(.ant-form-horizontal .ant-form-item-control){
// 	margin-left:-71px;
// }
:deep(.ant-form-item .ant-form-item-explain-error) {
    margin-top: -25px;
}

//:deep(.ant-upload-wrapper.ant-upload-picture-card-wrapper::after ){
//	margin-top:20px;
//	margin-left:-100px;
//}
:deep(.ant-form-item-explain .ant-form-item-explain-connected .ant-form-show-help) {
    margin-left: -30px;
}

// 右侧隐藏滚动条
::-webkit-scrollbar {
    display: none;
}
</style>